package cn.bluejoe.elfinder.servlet;

import cn.bluejoe.elfinder.flter.UserFilter;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    public final static String LOGIN = "login";


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        switch(action){
            case "login": doLogin(req, resp);break;
            case "isLogin": isLogin(req,resp);break;
            case "q": logOut(req,resp);break;
            default: resp.sendRedirect(req.getServletContext().getContextPath() + "/login.html");
        }
    }

    private void logOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        Object f = session.getAttribute(LOGIN);
        if(null != f && (Boolean) f){
            session.setAttribute(LOGIN, false);
            resp.sendRedirect(req.getServletContext().getContextPath() + "/login.html");
        }
    }

    private void isLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        Object f = session.getAttribute(LOGIN);
        if(null != f && (Boolean) f){
            resp.getWriter().write("true");
        }else {
            resp.getWriter().write("false");
        }

    }

    private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String u = req.getParameter("u");
        String p = req.getParameter("p");
        if("admin".equals(u) && UserFilter.password.equals(p)){
            HttpSession session = req.getSession();
            session.setAttribute(LOGIN, true);
            resp.sendRedirect(req.getServletContext().getContextPath() + "/index.html");

        }else{
            resp.sendRedirect(req.getServletContext().getContextPath() + "/login.html");
        }
    }
}
